package com.whfc.common.face.uniview;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.whfc.common.util.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * 宇视人脸识别服务
 */
@Slf4j
@Service
public class UniviewFaceRecognitionService {

    @Value("${uniview.face.api.url:https://faceapi.uniview.com}")
    private String apiUrl;

    @Value("${uniview.face.app.key:}")
    private String appKey;

    @Value("${uniview.face.app.secret:}")
    private String appSecret;

    /**
     * 人脸比对
     * @param faceImage1 人脸图片1 Base64
     * @param faceImage2 人脸图片2 Base64
     * @return 比对分数，大于阈值表示匹配成功
     */
    public Double faceCompare(String faceImage1, String faceImage2) {
        try {
            Map<String, String> params = new HashMap<>();
            params.put("appKey", appKey);
            params.put("timestamp", String.valueOf(System.currentTimeMillis()));
            params.put("image1", faceImage1);
            params.put("image2", faceImage2);

            // 生成签名
            String sign = generateSign(params, appSecret);
            params.put("sign", sign);

            String url = apiUrl + "/api/v1/face/compare";
            String response = HttpUtil.doPost(url, JSON.toJSONString(params));

            JSONObject result = JSON.parseObject(response);
            if (result != null && "0".equals(result.getString("code"))) {
                return result.getDouble("score");
            } else {
                log.error("宇视人脸比对失败: {}", result != null ? result.getString("msg") : "未知错误");
                return null;
            }
        } catch (Exception e) {
            log.error("宇视人脸比对异常: {}", e.getMessage(), e);
            return null;
        }
    }

    /**
     * 人脸特征提取
     * @param faceImage 人脸图片Base64
     * @return 人脸特征向量
     */
    public String extractFaceFeature(String faceImage) {
        try {
            Map<String, String> params = new HashMap<>();
            params.put("appKey", appKey);
            params.put("timestamp", String.valueOf(System.currentTimeMillis()));
            params.put("image", faceImage);

            String sign = generateSign(params, appSecret);
            params.put("sign", sign);

            String url = apiUrl + "/api/v1/face/feature";
            String response = HttpUtil.doPost(url, JSON.toJSONString(params));

            JSONObject result = JSON.parseObject(response);
            if (result != null && "0".equals(result.getString("code"))) {
                return result.getString("feature");
            } else {
                log.error("宇视人脸特征提取失败: {}", result != null ? result.getString("msg") : "未知错误");
                return null;
            }
        } catch (Exception e) {
            log.error("宇视人脸特征提取异常: {}", e.getMessage(), e);
            return null;
        }
    }

    /**
     * 生成签名
     */
    private String generateSign(Map<String, String> params, String secret) {
        // 按参数名排序后拼接
        String signStr = params.entrySet().stream()
                .sorted(Map.Entry.comparingByKey())
                .map(entry -> entry.getKey() + "=" + entry.getValue())
                .reduce((a, b) -> a + "&" + b)
                .orElse("");
        signStr += secret;

        // 使用MD5生成签名
        return org.apache.commons.codec.digest.DigestUtils.md5Hex(signStr);
    }
}